/*

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/
#import "MusicView.h"
#import <UIKit/UIPreferencesTable.h>
#import <UIKit/UIProgressIndicator.h>
#import "XBMCControlApplication.h"
#import "XBMCHttpInterface.h"
#import "MediaItem.h"

@implementation MusicView

- (id) initWithApplication: (UIApplication*)app withAppID: (NSString*)appID withFrame: (struct CGRect)rect
{
    self = [super initWithFrame: rect];
	m_viewIsActive = NO;
	m_rect = rect;
	m_xbmc = [XBMCHttpInterface sharedInstance];
	m_mainApp = (XBMCControlApplication*)app;
	m_CellArray = [[NSMutableArray alloc] init];
    m_table = [[UITable alloc] initWithFrame: CGRectMake(0.0f, 48.0f, rect.size.width, rect.size.height - 48.0f)];
	[self addSubview: m_table];
	UITableColumn *col = [[UITableColumn alloc] initWithTitle: @"XBMCMusic"
        identifier: @"xbmc" width: 320.0f];
    [m_table addTableColumn: col];
	
	[m_table setDataSource: self];
    [m_table setDelegate: self];
	
	// nav bar
    m_navBar = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, rect.size.width, 48.0f)] autorelease];
    [m_navBar showLeftButton:@"Main Menu" withStyle:0 rightButton:@"Refresh" withStyle:3];
    [m_navBar setBarStyle:0];
    [m_navBar setDelegate:self];
	[self addSubview: m_navBar];
	
	// create, offscreen
	m_bottomNavBar = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0.0f, rect.size.height, rect.size.width, 48.0f)] autorelease];
    [m_bottomNavBar setBarStyle:0];
	[self addSubview: m_bottomNavBar];
	float segWidth = 300.0f;
	m_bottomButtonPanelMusicItemRect = CGRectMake(320.0f / 2.0f - (segWidth / 2.0f), 6.0f, segWidth, 30.0f);
	m_bottomButtonPanelMusicItem = [[UISegmentedControl alloc] initWithFrame:m_bottomButtonPanelMusicItemRect withStyle:2 withItems:nil];
	[m_bottomButtonPanelMusicItem insertSegment:0 withTitle:@"Play" animated:NO];
	[m_bottomButtonPanelMusicItem insertSegment:1 withTitle:@"Queue" animated:NO];
	[m_bottomButtonPanelMusicItem insertSegment:2 withTitle:@"Get Info" animated:NO];
	[m_bottomButtonPanelMusicItem setMomentaryClick:YES];
	[m_bottomButtonPanelMusicItem setDelegate:self];
	[m_bottomNavBar addSubview: m_bottomButtonPanelMusicItem];
	m_bottomButtonPanelPlaylistRect = CGRectMake(320.0f / 2.0f - (segWidth / 2.0f), 6.0f, segWidth, 30.0f);
	m_bottomButtonPanelPlaylist = [[UISegmentedControl alloc] initWithFrame:m_bottomButtonPanelPlaylistRect withStyle:2 withItems:nil];
	[m_bottomButtonPanelPlaylist insertSegment:0 withTitle:@"Play" animated:NO];
	[m_bottomButtonPanelPlaylist insertSegment:1 withTitle:@"Queue" animated:NO];
	[m_bottomButtonPanelPlaylist insertSegment:2 withTitle:@"View" animated:NO];
	[m_bottomButtonPanelPlaylist setMomentaryClick:YES];
	[m_bottomButtonPanelPlaylist setDelegate:self];
	[m_bottomNavBar addSubview: m_bottomButtonPanelPlaylist];
	m_isBottomBarShown = false;
	
	UINavigationItem *title = [[[UINavigationItem alloc] initWithTitle:@"Music"] autorelease];
    [m_navBar pushNavigationItem:title];
	
	//m_progress = [[UIProgressHUD alloc] initWithFrame:CGRectMake(50,50, 20, 20)];
	//progressIndicator = [[UIProgressIndicator alloc] initWithFrame:CGRectMake(300,10, 20, 20)];
        // [m_progress setAnimationDuration:10];
        // [m_progress setStyle:0];
        // [m_progress startAnimation];
	// [m_table addSubview: m_progress];
	
	// [m_progress setText: @"crap"];
	// [m_progress drawRect: CGRectMake(50,50, 20, 20)];
	// [m_progress show: NO];

	// [self addSubview:m_progress];
	
	m_folderItemCache = [[NSMutableDictionary dictionaryWithCapacity:10] retain];
	
	m_currentFolderName = @"";
	m_folderStack = [[NSMutableArray alloc]initWithCapacity:10];

	return self;
}

-(void)dealloc
{
   [m_currentFolderName release];
   [m_folderItemCache release];
   [super dealloc];
}


-(MediaItemFactory*)getMediaItemFactory
{
   if (m_mediaItemFactory == nil)
   {
      m_mediaItemFactory = [[MediaItemFactory alloc] initWithExtensions: [m_xbmc getMusicExtensions] pictureExtensions:[m_xbmc getPictureExtensions] videoExtensions:[m_xbmc getVideoExtensions]];
   }
   return m_mediaItemFactory;
}

-(NSArray*)getCurrentFolderItems
{
   NSLog(@"getCurrentFolderItems");
   
   NSArray *mediaItems = [m_folderItemCache objectForKey:m_currentFolderName];
   if (mediaItems == nil)
   {
	   NSString *location = nil;
	   if ([m_currentFolderName length] > 0)
	   {
	      location = m_currentFolderName;
	   }	  
	   
	   mediaItems = [m_xbmc getMediaLocation: @"music" location: location];
	   [m_folderItemCache setObject:[mediaItems retain] forKey:m_currentFolderName];
   }
   else
   {
      NSLog(@"Found key for folder '%@' in dictionary, using cache", m_currentFolderName);
   }
      
   NSLog(@"getCurrentFolderItems done");
   return mediaItems;
}

-(void)populateTableWithItems:(NSArray*)itemArray
{
   NSLog(@"populateTableWithItems");
   [self clearTable];
   int i;
   for (i=0; i<[itemArray count]; ++i)
   {
      MediaItem* item = [itemArray objectAtIndex:i];
	  UIImageAndTextTableCell *cell = [[UIImageAndTextTableCell alloc] initWithFrame:CGRectMake(0.0f, 48.0f, m_rect.size.width, 48.0f)];
	  NSString* name = [item getName];
	  //NSLog(@"Item name: %@", name);
	  [cell setTitle:name];
	  [cell setShowDisclosure:([item getType]==kFolder)];
	  [cell setSelected:NO];
	  UIImage* icon = [item getIcon];
	  if (icon != nil)
	  {
	     UIImageView *iconView = [cell iconImageView];
	    [iconView setImage: icon];
	    [iconView setFrame: CGRectMake(0.0f, 0.0f, 29.0f, 29.0f)];
	  }
	  [m_CellArray addObject:cell];
   }
   [m_table selectRow:NSNotFound byExtendingSelection:NO withFade:NO];
   [m_table reloadData];
   m_currentTableItems = [[NSArray arrayWithArray:itemArray] retain];
   NSLog(@"populateTableWithItems done");
   
}

- (void)tableRowSelected:(NSNotification *)notification 
{
  int i = [m_table selectedRow];
  NSLog(@"tableRowSelected!  %d", i);
  [self hideBottomNavBar];
  if (i != NSNotFound)
  {
      NSLog(@"valid selection");
	  MediaItem* item = [m_currentTableItems objectAtIndex:i];
	  NSLog(@"got item");
	  if ([item getType] == kFolder)
	  {
	     NSLog(@"is folder");
	     // navigate to folder
		 [self navigateToChildFolder: [item getPath] withName:[item getName]];
	  }
	  else if ([item getType] == kPlaylist)
	  {
	     // display bottom
		 [self showBottomNavBar];
		 [self showPlaylistButtons];
	  }
	  else if ([item getType] == kMusic)
	  {
	     // display bottom
		 [self showBottomNavBar];
		 [self showMusicItemButtons];
	  }
	  else
	  {
	     // nothing for unknown items
	  }
  }
}

-(void)navigateToChildFolder:(NSString*)folder withName:(NSString*)name
{
    // push current folder (parent) into stack
    [m_folderStack insertObject:m_currentFolderName atIndex:0];
	[self navigateToFolder: folder];
	UINavigationItem *title = [[[UINavigationItem alloc] initWithTitle:name] autorelease];
    [m_navBar pushNavigationItem:title];
	[m_navBar showLeftButton:@"Up Dir" withStyle:0 rightButton:@"Refresh" withStyle:3];
}

-(void)navigateToParentFolder
{
   if ([m_currentFolderName length] > 0)
   {
      // pop stack
	  NSString *parentFolder = [m_folderStack objectAtIndex:0];
	  [m_folderStack removeObjectAtIndex:0];
	  [self navigateToFolder: parentFolder];
	  [m_navBar popNavigationItem];
	  if ([m_folderStack count] == 0)
	  {
	     [m_navBar showLeftButton:@"Main Menu" withStyle:0 rightButton:@"Refresh" withStyle:3];
	  }
   }
}

-(void)navigateToFolder:(NSString*)folder
{
    [m_currentFolderName release];
    m_currentFolderName = [folder retain];
	[self populateTableWithItems:[self getCurrentFolderItems]];
}

- (void) segmentedControl: (UISegmentedControl *)segment selectedSegmentChanged: (int)seg
{
	if (segment == m_bottomButtonPanelMusicItem)
	{
	    NSLog(@"Selected segm3ent: MusicItem %i", seg);
		switch (seg)
		{
			case 0:  
				{
				   // play
				   int i = [m_table selectedRow];
				   if (i != NSNotFound)
				   {
				      MediaItem* item = [m_currentTableItems objectAtIndex:i];
				      [m_xbmc playFile: [item getPath]];
				   }
				}
				break;
			case 1:
               {
				   // queue
				   int i = [m_table selectedRow];
				   if (i != NSNotFound)
				   {
				      MediaItem* item = [m_currentTableItems objectAtIndex:i];
				      [m_xbmc queueFile: [item getPath]];
				   }
				}			
				break;
			case 2:
				{
				   // get info
				   int i = [m_table selectedRow];
				   NSLog(@"table selected row %i", i);

				   if (i != NSNotFound)
				   {
				      NSLog(@"doing getInfo");
					  MediaItem* item = [m_currentTableItems objectAtIndex:i];
					  NSMutableDictionary* itemInfo = [m_xbmc getFileInfo: [item getPath]];
					  // display artist, title, album
					  NSArray* buttons = [NSArray arrayWithObjects:@"Close",nil];
					  UIAlertSheet* popup = [[UIAlertSheet alloc] initWithTitle:@"File Info" buttons:buttons defaultButtonIndex:0 delegate:self context:nil];
					  [popup setBodyText: @"Text Here"];
					  [popup popupAlertAnimated: TRUE];
				   }
				}
			break;
				
		}
	}
	if (segment == m_bottomButtonPanelPlaylist)
	{
	    NSLog(@"Selected segment: Playlist %i", seg);
		switch (seg)
		{
		    case 0:  
				{
				   // play
				   int i = [m_table selectedRow];
				   if (i != NSNotFound)
				   {
				      MediaItem* item = [m_currentTableItems objectAtIndex:i];
				      [m_xbmc playFile: [item getPath]];
				   }
				}
				break;
			case 1:
               {
				   // queue
				   int i = [m_table selectedRow];
				   if (i != NSNotFound)
				   {
				      MediaItem* item = [m_currentTableItems objectAtIndex:i];
				      [m_xbmc queueFile: [item getPath]];
				   }
				}			
				break;
			case 2:  
			{
			   // view playlist
			   int i = [m_table selectedRow];
               if (i != NSNotFound)
			   {
			      MediaItem* item = [m_currentTableItems objectAtIndex:i];
			      [self navigateToChildFolder: [item getPath] withName:[item getName]];
			   }
			}
			break;
		}
	}
}

- (void)alertSheet:(UIAlertSheet *)sheet buttonClicked:(int)button 
{
	[sheet dismissAnimated: TRUE];
}

-(void)showBottomNavBar
{
   if (m_isBottomBarShown == NO)
   {
      [m_table setFrame:CGRectMake(0.0f, 48.0f, m_rect.size.width, m_rect.size.height - 96.0f)];
	  [m_bottomNavBar setFrame:CGRectMake(0.0f, m_rect.size.height - 48.0, m_rect.size.width, 48.0f)];
	  m_isBottomBarShown = YES;
	}
}

-(void)hideBottomNavBar
{
   if (m_isBottomBarShown == YES)
   {
      [m_table setFrame:CGRectMake(0.0f, 48.0f, m_rect.size.width, m_rect.size.height - 48.0f)];
   	  [m_bottomNavBar setFrame:CGRectMake(0.0f, m_rect.size.height, m_rect.size.width, 48.0f)];

	  m_isBottomBarShown = NO;
   }
}

-(void)showMusicItemButtons
{
   [m_bottomButtonPanelMusicItem setFrame:m_bottomButtonPanelMusicItemRect];
   [m_bottomButtonPanelPlaylist setFrame:
      CGRectMake(m_bottomButtonPanelPlaylistRect.origin.x, m_bottomButtonPanelPlaylistRect.origin.y+100,
	  m_bottomButtonPanelPlaylistRect.size.width, m_bottomButtonPanelPlaylistRect.size.height)];
}

-(void)showPlaylistButtons
{
   [m_bottomButtonPanelPlaylist setFrame:m_bottomButtonPanelPlaylistRect];
   [m_bottomButtonPanelMusicItem setFrame:
      CGRectMake(m_bottomButtonPanelMusicItemRect.origin.x, m_bottomButtonPanelMusicItemRect.origin.y+100,
	  m_bottomButtonPanelMusicItemRect.size.width, m_bottomButtonPanelMusicItemRect.size.height)];
}

-(void)activateView
{
   NSLog(@"activateView");
   if (m_viewIsActive == NO)
   {
      // JOEBUG: do we want the music view to always come up when folder is activated?
      [self navigateToFolder: @""];
	   m_viewIsActive = YES;
   }
   NSLog(@"activateView done");
}

-(void)deactivateView
{
   if (m_viewIsActive == YES)
   {
	   [self clearTable];
	   [m_table reloadData];
	   m_viewIsActive = NO;
   }
}

-(void)clearTable
{
   int i;
   for (i=0; i<m_CellArray.count; ++i)
   {
	  [[m_CellArray objectAtIndex:i] release];
   }
   [m_CellArray removeAllObjects];
}

-(UITable*)table
{
   return m_table;
}

- (int) numberOfRowsInTable: (UITable *)table
{
    return [m_CellArray count];
}

- (UITableCell *) table: (UITable *)table cellForRow: (int)row column: (int)col
{
	return [m_CellArray objectAtIndex:row];
}

- (void)navigationBar:(id)navbar buttonClicked:(int)button
{
    if (navbar == m_navBar)
	{
	    switch (button)
	    {
	        case 0:
	            // nothing
	            break;
	        case 1:
	            // transition to main menu
				if ([m_folderStack count] == 0)
				{
				   [m_mainApp transitionToMainMenu];
				}
				else
				{
				   [self navigateToParentFolder];
				}
	            break;
	    }
	}
}

@end

